<template>
  <dialog_item :dialogTitle="isBatch?'批量授权':'角色授权'" @onBtnDialogClick="onBtnDialogClick" :visible.sync="dialogVisible" dialogClass="dialogHeight  rolePermission" :isShowConfirmBtn="true">
    <div class="height100">
      <div v-if="isBatch">
        <el-row>
          <el-col :span="24">
            <p class="smallHeader rolePerTipP">角色选择<span class="rolePerTip">(选择需要批量授权的角色，此次设置将会清空角色原来的授权设置，未选择的角色将不受影响。)</span></p>
            <el-select v-model="roleIds" multiple :placeholder="$t('placeholder_select')" class="selectRoles" size="mini">
              <el-option
                v-for="item in roles"
                :key="item.roleId"
                :label="item.roleName"
                :value="item.roleId">
              </el-option>
            </el-select>
          </el-col>
          
        </el-row>
        
      </div>
      <el-row :gutter="24"  :class="[isBatch?'mainDetail':' height100']">
        <el-col :span="8" class="height100">
          <el-tabs v-model="activeName" type="border-card"  class="height100 rolePermissionTabs">
            <el-tab-pane label="PC端菜单" name="pc" class="height100">
              <el-button type="text" class="miniFontSize padding0" @click="changePCExpandAll(true)">打开所有</el-button>
              <el-button type="text" class="miniFontSize padding0" @click="changePCExpandAll(false)">关闭所有</el-button>
              <el-scrollbar  class="scrollBarHeight" :native="false">
                <el-tree
                  ref="pcTree"
                  node-key="id"
                  :props="{
                    label: 'name',
                    children: 'zones',
                    isLeaf: isLeaf,
                    disabled:isDis,
                  }"
                  :load="loadNode"
                  :expand-on-click-node="false"
                  lazy
                  show-checkbox
                  :default-checked-keys="defaultChecked"
                  :default-expanded-keys="defaultExpandedKeys"
                  :default-expand-all="pcExpandAll"
                  :check-strictly='true'
                  @check-change="checkAllPcNode"
                ></el-tree>
              </el-scrollbar>
            </el-tab-pane>
            <el-tab-pane label="移动端菜单" name="mobile" class="height100">
              <el-button type="text" class="miniFontSize padding0" @click="changeMobileExpandAll(true)">打开所有</el-button>
              <el-button type="text" class="miniFontSize padding0" @click="changeMobileExpandAll(false)">关闭所有</el-button>
              <el-scrollbar class="scrollBarHeight" :native="false">
                <el-tree
                  ref="mobileTree"
                  node-key="id"
                  :props="{
                    label: 'name',
                    children: 'zones',
                    isLeaf: isLeaf,
                    disabled:isDis,
                  }"
                  :load="loadMobileNode"
                  :expand-on-click-node="false"
                  lazy
                  show-checkbox
                  :default-checked-keys="defaultMobileChecked"
                  :default-expanded-keys="defaultMobileExpandedKeys"
                  :default-expand-all="mobileExpandAll"
                  :check-strictly='true'
                  @check-change="checkAllMobileNode"
                ></el-tree>
              </el-scrollbar>
            </el-tab-pane>
            <el-tab-pane label="模块资源" name="module" class="height100">
              <el-button type="text" class="miniFontSize padding0" @click="changeModuleExpandAll(true)">打开所有</el-button>
              <el-button type="text" class="miniFontSize padding0" @click="changeModuleExpandAll(false)">关闭所有</el-button>
              <el-scrollbar class="scrollBarHeight" :native="false">
                <el-tree
                  ref="tree"
                  node-key="id"
                  :props="{
                    label: 'name',
                    children: 'zones',
                    isLeaf: isLeaf,
                  }"
                  :load="loadModuleNode"
                  :expand-on-click-node='false'
                  lazy
                  :default-expanded-keys="defaultModuleExpandedKeys"
                  @node-click="moduleTreeClick"
                  :default-expand-all="moduleExpandAll"
                ></el-tree>
              </el-scrollbar>
            </el-tab-pane>
          </el-tabs>
        </el-col>
        <el-col :span="16" class="height100">
          <div v-if="activeName=='module'&& haveData " class="height100 ">
            <el-scrollbar class="height100" :native="false">
              <el-form label-position="top" size="mini">
                <el-row>
                  <el-col class="labelMarginBot0">
                    <el-form-item label="表单资源" class="rolePermissionModule">
                      <el-checkbox  v-model="checkFormAll" @change="handleCheckFormAllChange">全选</el-checkbox>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row v-for="(elm) in moduleResource.forms" :key="elm.id" class="marginBot5">
                  <el-col>
                    <el-row>
                      {{elm.name}}[{{elm.permissionType=="public"?'公共':'私有'}}]:
                    </el-row>
                    <el-row>
                      <el-col v-for="(el) in elm.activities" :key="el.id" class="widthAuto">
                        <el-form-item :label="el.name" class="rolePermissionModule ">
                          <el-checkbox v-model="el.checked"  :disabled="elm.permissionType=='public'?true:false"></el-checkbox>
                        </el-form-item>
                      </el-col>
                      
                    </el-row>
                    
                  </el-col>
                </el-row>
                <el-row>
                  <el-col>
                    <el-form-item label="视图资源" class="rolePermissionModule marginTop10">
                      <el-checkbox  v-model="checkViewAll"  @change="handleCheckViewAllChange">全选</el-checkbox>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row v-for="(elm) in moduleResource.views" :key="elm.id" class="marginBot5">
                  <el-col>
                    <el-row>
                      {{elm.name}}[{{elm.permissionType=="public"?'公共':'私有'}}]:
                    </el-row>
                    <el-row>
                      <el-col v-for="(el) in elm.activities" :key="el.id" class="widthAuto" >
                        <el-form-item :label="el.name" class="rolePermissionModule">
                          <el-checkbox v-model="el.checked"  :disabled="elm.permissionType=='public'?true:false"></el-checkbox>
                        </el-form-item>
                      </el-col>
                      
                    </el-row>
                    
                  </el-col>
                </el-row>
                
              </el-form>
            </el-scrollbar>
          </div>
        </el-col>
      </el-row>
    </div>
    </dialog_item>
</template>

<script>
export default {
  props: ["visible","applicationId","roleId","roles","isBatch"],
  created() {
    
  },
  data() {
    return {
      activeName:'pc',
      defaultChecked:[],
      defaultExpandedKeys:[],
      defaultMobileChecked:[],
      defaultMobileExpandedKeys:[],

      defaultModuleExpandedKeys:[],

      moduleResource:[],
      checkFormAll:false,
      checkViewAll:false,
      resources:[],
      views:[],
      forms:[],
      roleIds:[],
      pcExpandAll:false,
      node:null,
      resolve:null,
      first:true,
      mobileExpandAll:false,
      mobilenode:null,
      mobileresolve:null,
      mobilefirst:true,

      moduleExpandAll:false,
      modulenode:null,
      moduleresolve:null,
      modulefirst:true,

      haveData:false,

      pcCanCheck:[],
      mobileCanCheck:[],
      haveCheckModule:[],//切换模块资源的时候保存已选中的资源
    };
  },
  computed: {
    dialogVisible: {
      get() {
        return this.visible;
      },
      set(val) {
        this.$emit("update:visible", val);
      }
    }
  },
  methods: {
    onBtnDialogClick(name){
      if(name=='confirm') this.onOk()
    },
    checkAllPcNode(data,val){
      // if(!val){

      // }
      if(data.id==this.applicationId){
        if(val){
          this.pcCanCheck.forEach(elm=>{
            this.$refs.pcTree.setChecked(elm,true);
          })
        }else{
          this.pcCanCheck.forEach(elm=>{
            this.$refs.pcTree.setChecked(elm,false);
          })
        }
      }
    },
    checkAllMobileNode(data,val){
      if(data.id==this.applicationId){
        if(val){
          this.mobileCanCheck.forEach(elm=>{
            this.$refs.mobileTree.setChecked(elm,true);
          })
        }else{
          this.mobileCanCheck.forEach(elm=>{
            this.$refs.mobileTree.setChecked(elm,false);
          })
        }
      }
    },
    changePCExpandAll(val){
      this.pcExpandAll=val;
      this.loadNode(this.node,this.resolve)
    },
    changeMobileExpandAll(val){
      this.mobileExpandAll=val;
      this.loadMobileNode(this.mobilenode,this.mobileresolve)
    },
    changeModuleExpandAll(val){
      this.moduleExpandAll=val;
      this.loadModuleNode(this.modulenode,this.moduleresolve)
    },
    handleCheckFormAllChange(val){
      this.moduleResource.forms.forEach(elm=>{
        if(elm.permissionType=="private"){
          elm.activities.forEach(el=>{
            el.checked=val
          })
        }
      })
      this.checkFormAll=val;
    },
    handleCheckViewAllChange(val){
      this.moduleResource.views.forEach(elm=>{
        if(elm.permissionType=="private"){
          elm.activities.forEach(el=>{
            el.checked=val
          })
        }
      })
      this.checkViewAll=val;
    },
    isDis(data){
      if(data.permissionType=="public"){
        return true;
      }else{
        return false;
      }
    },
    isLeaf(data){
      if(!data.hasChild){
        return true;
      }else{
        return false;
      }
    },
    onCancel(){
      this.$emit("update:visible", false);
    },
    onOk(){
      let that=this;
      let data={};
      data.roles=[]
      if(this.isBatch){
        data.roles=this.roleIds;
      }else{
        data.roles.push(this.roleId);
      }
      // let checkedTreeNode=[...this.$refs.pcTree.getCheckedNodes(),...this.$refs.mobileTree.getCheckedNodes()];
      // checkedTreeNode.forEach(elm=>{
      //   if(elm.permissionType=="private"){
      //     this.resources.push(elm.id);
      //   }
      // })
      this.pcCanCheck.forEach(elm=>{
        let data={};
        data.id=elm;
        data.checked=that.$refs.pcTree.getNode(elm).checked;
        this.resources.push(data)
      })
      this.mobileCanCheck.forEach(elm=>{
        let data={};
        data.id=elm;
        data.checked=that.$refs.mobileTree.getNode(elm).checked;
        this.resources.push(data)
      })
      
      data.resources=this.resources;
      if(this.moduleResource && this.moduleResource.forms && this.moduleResource.views){
        this.moduleResource.forms.forEach(elm=>{
          that.forms.forEach((elem,ind)=>{
            if(elm.id==elem.id){
              that.forms.splice(ind,1);
            }
          })
          if(elm.permissionType=="private"){
            let change={
              "id": elm.id,
              "activities": []
            };
            elm.activities.forEach(el=>{
              let data={}
              data.id=el.id;
              data.checked=el.checked;
              change.activities.push(data);
            })
            if(change.activities.length>0){
              that.forms.push(change);
            }
            
          }
        })
        this.moduleResource.views.forEach(elm=>{
          that.forms.forEach((elem,ind)=>{
            if(elm.id==elem.id){
              that.views.splice(ind,1);
            }
          })
          if(elm.permissionType=="private"){
            let change={
              "id": elm.id,
              "activities": []
            };
            elm.activities.forEach(el=>{
              let data={}
              data.id=el.id;
              data.checked=el.checked;
              change.activities.push(data);
            })
            if(change.activities.length>0){
              that.views.push(change);
            }
          }
        })
      }
      
      
      data.views=this.views;
      data.forms=this.forms;

      this.$api.savePermission({applicationId:this.applicationId,data:data}, {
        onSucess: resp => {
          if(resp.data.errcode==0){
            this.$message({
              showClose: true,
              message: resp.data.data,
              type: "success"
            });
            this.$emit("update:visible", false);
          }
        }
      });
    },
    loadNode(node, resolve) {
      let that=this;
      console.log(node);
      if (node.level === 0 ) {
        if(this.first){
          this.first=false;
          this.node=node;
          this.resolve=resolve;
        }
        this.node.childNodes = [];
        this.defaultExpandedKeys=[];
        let root =[{
          checked: true,
          id: this.applicationId,
          name: "所有菜单",
          parentId: "",
          permissionType: "private",
        }]
        resolve(root);
        this.defaultExpandedKeys.push(this.applicationId)
      }
      if (node.level >= 1 ) {
        
        this.$api.getPCmenu({applicationId:this.applicationId,roleId:this.roleId,parentId:node.key}, {
          onSucess: resp => {
            if(resp.data.data){
              let subdepts = resp.data.data;
              subdepts.forEach(elm=>{
                if(elm.checked){
                  this.defaultChecked.push(elm.id)
                }
                if(elm.hasChild && that.pcExpandAll){
                  this.defaultExpandedKeys.push(elm.id)
                }
                if(elm.permissionType=="private"){
                  this.pcCanCheck.push(elm.id);
                }
              })
              resolve(subdepts);
            }
            
          }
        });
      }
    },
    loadMobileNode(node, resolve){
      let that=this;
      if (node.level === 0 ) {
        if(this.mobilefirst){
          this.mobilefirst=false;
          this.mobilenode=node;
          this.mobileresolve=resolve;
        }
        this.mobilenode.childNodes = [];
        this.defaultMobileExpandedKeys=[];

        let root =[{
          checked: true,
          id: this.applicationId,
          name: "所有菜单",
          parentId: "",
          permissionType: "private",
        }]
        resolve(root);
        this.defaultMobileExpandedKeys.push(this.applicationId)
      }
      if (node.level >= 1 ) {
        
        this.$api.getMobilemenu({applicationId:this.applicationId,roleId:this.roleId,parentId:node.key}, {
          onSucess: resp => {
            let subdepts = resp.data.data;
            subdepts.forEach(elm=>{
              if(elm.checked){
                this.defaultMobileChecked.push(elm.id)
              }
              if(elm.hasChild && that.mobileExpandAll){
                this.defaultMobileExpandedKeys.push(elm.id)
              }
              if(elm.permissionType=="private"){
                this.mobileCanCheck.push(elm.id);
              }
            })
            resolve(subdepts);
          }
        });
      }
    },
    loadModuleNode(node, resolve){
      let that=this;
      if (node.level === 0 ) {
        if(this.modulefirst){
          this.modulefirst=false;
          this.modulenode=node;
          this.moduleresolve=resolve;
        }
        this.modulenode.childNodes = [];
        this.defaultModuleExpandedKeys=[];
        let root =[{
          checked: true,
          id: this.applicationId,
          name: "所有模块",
          parentId: "",
          permissionType: "public",
        }]
        this.defaultModuleExpandedKeys.push(this.applicationId)
        resolve(root);
      }
      if (node.level >= 1) {
        this.$api.getModuleList({applicationId:this.applicationId,parentId:node.key}, {
          onSucess: resp => {
            let subdepts = resp.data.data;
            subdepts.forEach(elm=>{
              if(elm.hasChild && that.moduleExpandAll){
                this.defaultModuleExpandedKeys.push(elm.id)
              }
            })
            resolve(subdepts);
          }
        });
      }
    },
    //模块资源树节点点击事件
    moduleTreeClick(data){
      let that=this;
      
      //this.forms维护的是确定的时候要传给后台的数据
      if(this.moduleResource && this.moduleResource.forms && this.moduleResource.views){
        this.moduleResource.forms.forEach(elm=>{
          that.forms.forEach((elem,ind)=>{
            if(elm.id==elem.id){
              that.forms.splice(ind,1);
            }
          })
          if(elm.permissionType=="private"){
            let change={
              "id": elm.id,
              "activities": []
            };
            elm.activities.forEach(el=>{
              let data={}
              data.id=el.id;
              data.checked=el.checked;
              change.activities.push(data);
            })
            if(change.activities.length>0){
              
              that.forms.push(change);
            }
            
          }
        })
        this.moduleResource.views.forEach(elm=>{
          that.views.forEach((elem,ind)=>{
            if(elm.id==elem.id){
              that.views.splice(ind,1);
            }
          })
          if(elm.permissionType=="private"){
            let change={
              "id": elm.id,
              "activities": []
            };
            elm.activities.forEach(el=>{
              let data={}
              data.id=el.id;
              data.checked=el.checked;
              change.activities.push(data);
            })
            if(change.activities.length>0){
              that.views.push(change);
            }
          }
        })
      }

      this.moduleResource=[];
      this.$api.getModuleResource({applicationId:this.applicationId,roleId:this.roleId,moduleId:data.id}, {
        onSucess: resp => {
          this.moduleResource=resp.data.data;
          if(this.moduleResource.forms||this.moduleResource.views){
            if(this.moduleResource.forms.length>0||this.moduleResource.views.length>0){
              this.haveData=true;
              that.forms.forEach(elm=>{
                for(let i=0;i<that.moduleResource.forms.length;i++){
                  if(elm.id==that.moduleResource.forms[i].id){
                    elm.activities.forEach(el=>{
                      for(let j=0;j<that.moduleResource.forms[i].activities.length;j++){
                        if(el.id==that.moduleResource.forms[i].activities[j].id){
                          that.moduleResource.forms[i].activities[j].checked=el.checked;
                          break;
                        }
                      }
                    })
                    break;
                  }
                }
              })
              that.views.forEach(elm=>{
                for(let i=0;i<that.moduleResource.views.length;i++){
                  if(elm.id==that.moduleResource.views[i].id){
                    elm.activities.forEach(el=>{
                      for(let j=0;j<that.moduleResource.views[i].activities.length;j++){
                        if(el.id==that.moduleResource.views[i].activities[j].id){
                          that.moduleResource.views[i].activities[j].checked=el.checked;
                          break;
                        }
                      }
                    })
                    break;
                  }
                }
              })
            }
          }

        }
      });
    },
    
  }
};
</script>

<style>
</style>